// 2013-8-1下午02:20:14  net.betou.trade.admin.action.UserAct.java

package net.betou.trade.admin.action;

import static net.betou.common.page.SimplePage.cpn;
import static net.betou.common.page.SimplePage.cpnPageSize;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.betou.common.page.Pagination;
import net.betou.common.util.TradeUtils;
import net.betou.common.web.RequestUtils;
import net.betou.trade.action.abs.ActionSupport;
import net.betou.trade.entity.main.AgentAndAdmins;
import net.betou.trade.entity.main.User;
import net.betou.trade.entity.main.UserExt;
import net.betou.trade.main.manager.PictureMng;
import net.betou.trade.main.manager.UserGroupMng;
import net.betou.trade.main.manager.UserMng;
import net.betou.trade.web.Messages;
import net.betou.trade.web.ResponseUtil;
import net.betou.trade.web.WebErrors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 
 * @author 叶装装
 */
@Controller
public class UserAct extends ActionSupport< User >{
	private static final Logger log = LoggerFactory.getLogger( UserAct.class );
	
	private static final String DIRECTORY = "user";
	
	@RequestMapping( "/user/v_list.jspx" )
	public String list( Integer pageSize, Integer pageNo, String filterStatus, String searchProperty, String searchValue, String orderProperty, String orderDirection, HttpServletRequest request, HttpServletResponse response, ModelMap model  ){
		
		pageSize = cpnPageSize( pageSize );
		pageNo = cpn( pageNo );
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request );
		
		Pagination pagination = manager.getPage( admin, searchProperty, searchValue, orderProperty, orderDirection, pageNo, pageSize, filterStatus );
	
		model.addAttribute( "groupList", groupMng.getAllList( null, null, null, null ) );
		model.addAttribute( "admin", admin );	
		paramToModel( model, pagination, null, pageSize, searchProperty, searchValue, orderProperty, orderDirection, filterStatus );
		return getListPage( );
	}
	
	@RequestMapping( "/user/v_add.jspx" )
	public String v_add( HttpServletRequest request, ModelMap model ){
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request );
		WebErrors errors = validateToSave( admin );
		
		if( errors.hasErrors( ) ){
			return errors.showErrorPage( model );
		}
		
		model.addAttribute( "groupList", groupMng.getAllList( null, null, null, null ) );
		return getAddPage( );
	}
	
	@RequestMapping( "/user/o_save.jspx" )
	public String o_save( User bean, UserExt ext,  String [ ] pic, Integer groupId,  HttpServletRequest request, HttpServletResponse response, ModelMap model ){
		
		WebErrors errors = validateSave( bean, groupId );
		
		if( errors.hasErrors( ) ){
			return errors.showErrorPage( model );
		}
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request );
		
		String ip = RequestUtils.getIpAddr( request );
		bean = manager.save( admin, groupId, ip, bean, ext );
		
		if( pic != null ){
			for( String p : pic ){
				picMng.save( null, p, bean.getId( ) );
			}
		}
		
		logMng.operating( 0, request, Messages.LOG_USER, "id=" + bean.getId( ) + ",username=" + bean.getUsername( ));
		
		return "redirect:v_list.jspx";
	}
	
	
	@RequestMapping ( "/user/v_edit.jspx" )
	public String v_edit( Integer id, HttpServletRequest request, ModelMap model ){

		WebErrors errors = validateUpdate( request, id );
		
		if( errors.hasErrors( ) ){
			return errors.showErrorPage( model );
		}
		
		User bean = manager.findById( id );
		
		model.addAttribute( "bean", bean );
		model.addAttribute( "groupList", groupMng.getAllList( null, null, null, null ) );
		
		return getUpdatePage( );
	}
	
	@RequestMapping ( "/user/o_update.jspx" )
	public String o_update( Boolean disabled,  Integer id, String password, String expireDate, String mobile,
											String [] pic, Integer[] picIds, Byte status, 
										 	String email,  Integer groupId, String demoAccount, String demoAccountPwd, String firmAccount, String firmAccountPwd,
										 	UserExt ext, HttpServletRequest request, ModelMap model ){
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request );
		
		WebErrors errors = validateOUpdate( id, admin.getSystem( ), admin.getId( ), request );
		
		if( errors.hasErrors( ) ){
			return errors.showErrorPage( model );
		}
		
		User bean = manager.findById( id );
		
		bean = manager.update( status, expireDate, groupId, email, password, mobile, disabled, demoAccount, demoAccountPwd, firmAccount, firmAccountPwd, bean, ext );
		
		if( picIds != null ){
			picMng.deleteByIds( picIds );
		}
		
		if( pic != null ){
			for( String p : pic ){
				 picMng.save( null, p, bean.getId( ) );
			}
		}
		
		
		logMng.operating( 1, request, Messages.LOG_USER, "id=" + bean.getId( ) + ",username=" + bean.getUsername( ));
		
		return "redirect:v_list.jspx";
	}
	
	@RequestMapping( "/user/o_delete.jspx" )
	public void o_delete( Integer [ ] ids, HttpServletResponse response, HttpServletRequest request ){
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request );
		
		ResponseUtil util = validateDelete( ids, admin.getSystem( ), admin.getId( ), response, request );

		if( util.hasResponse( ) ){
			util.renderJson( );
			return;
		}

		User [ ] beans = manager.deleteByIds( ids );

		for ( User bean : beans ){
			log.info( "delete User id={}", bean.getId( ) );
			
			logMng.operating( 2, request, Messages.LOG_USER, "id=" + bean.getId( ) + ",username=" + bean.getUsername( ));
		}

		util.addSuccessResponse( Messages.getDeleteSuccessMessage( beans.length ) );

		util.renderJson( );
		return;
		
	}
	
	
	private ResponseUtil validateDelete( Integer [ ] ids, Boolean system, Integer adminId, HttpServletResponse response, HttpServletRequest request ) {
		ResponseUtil util = ResponseUtil.create( response );

		if( ids == null || ids.length == 0 ){
			util.addErrorResponse( Messages.DATA_NOT_SELECT );
			return util;
		}
		for ( Integer id : ids ){
			User user = manager.findMyUser( id, adminId, system );
			if( user == null ){
				util.addErrorResponse( system ? Messages.getNotExistMessage( id ) : Messages.DATA_NOT_OPERATING ); // 只要有一个数据不存在就提示不可删除
				break;
			}
		}
		return util;
	}
	
	
	
	/**
	 * @param request
	 * @param id
	 * @return
	 */
	private WebErrors validateUpdate( HttpServletRequest request, Integer id ){
		WebErrors errors = WebErrors.create( );
		
		if( id == null || id == 0 ){
			errors.addError( Messages.DATA_NOT_EXIST );
			return errors;
		}
		
		User user = manager.findById( id );
		if( user == null ){
			errors.addError( Messages.DATA_NOT_EXIST );
			return errors;
		}
		
		return errors;
			
	}
	
	private WebErrors validateOUpdate( Integer id, Boolean system, Integer selfId, HttpServletRequest request ){
		WebErrors errors = WebErrors.create( );
		
		if( id == null || id == 0 ){
			errors.addError( Messages.DATA_NOT_EXIST );
			return errors;
		}
		
		User user = manager.findMyUser( id, selfId, system );
		if( user == null ){
			errors.addError( system ? Messages.DATA_NOT_EXIST : Messages.DATA_NOT_OPERATING);
			return errors;
		}
		
		return errors;
	}
	
	private WebErrors validateToSave( AgentAndAdmins admin ){
		WebErrors errors = WebErrors.create( );
//		if( admin.getSystem( ) ){
//			errors.addError( Messages.USER_ADMIN_SYSTEM_MANAGER_NOT_TO_ADD );
//		}
		return errors;
	}
	
	private WebErrors validateSave( User bean,  Integer groupId ){
		WebErrors errors = WebErrors.create( );
		if( groupId == null || groupId == 0){
			errors.addError( Messages.USER_GROUP_NOT_EXIST );
		}
		return errors;
	}
	
	
	@Override
	protected String getDirectory( ) {
		return DIRECTORY;
	}
	
	@Autowired
	private UserMng manager;
	@Autowired
	private UserGroupMng groupMng;
	
	@Autowired
	private PictureMng picMng;

}
